;;; guile-openai --- An OpenAI API client for Guile
;;; Copyright © 2023 Andrew Whatson <whatson@tailcall.au>
;;;
;;; This file is part of guile-openai.
;;;
;;; guile-openai is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Affero General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; guile-openai is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with guile-openai.  If not, see
;;; <https://www.gnu.org/licenses/>.

(define-module (openai utils colorized)
  #:use-module (ice-9 colorized)
  #:export (color-stream)
  #:re-export (add-color-scheme!))

(define color-stream
  ;;; XXX: The guile-colorized library renders objects into a string
  ;;; before colorization, which breaks objects with streaming display.
  ;;; This custom color hack behaves correctly in the repl, but doesn't
  ;;; respect the port argument to colorize.  Needs fixing upstream.
  (let ((color-scheme-obj     (@@ (ice-9 colorized) color-scheme-obj))
        (color-scheme-color   (@@ (ice-9 colorized) color-scheme-color))
        (color-scheme-control (@@ (ice-9 colorized) color-scheme-control)))
    (lambda (cs)
      (let* ((dummy ((color-func)
                     (color-scheme-color cs) "x"
                     (color-scheme-control cs)))
             (parts (string-split dummy #\x)))
        (display (car parts))
        (display (color-scheme-obj cs))
        (display (cadr parts))
        ""))))
